﻿#region File Header
/***********************************************************************
 * Copyright © 2013 Beals Software
 * All Rights Reserved
************************************************************************
Author: Donald Beals
Date: February 18th, 2013
Description: TODO: Write a description of this file here.
****************************** Change Log ******************************
02.18.13 - Created initial file. (dbeals)
***********************************************************************/
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
#endregion

namespace GameJoltServices.Saves
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class GameSave
	{
		#region Properties
		public string Username
		{
			get;
			set;
		}

		public string UserToken
		{
			get;
			set;
		}

		public string Location
		{
			get;
			set;
		}

		public string Name
		{
			get;
			set;
		}

		public DateTime DateSaved
		{
			get;
			set;
		}

		public string DescriptionData
		{
			get;
			set;
		}

		public string SaveData
		{
			get;
			set;
		}

		public bool NeedsToBeDownloaded
		{
			get;
			set;
		}

		public bool IsCached
		{
			get
			{
				return !string.IsNullOrWhiteSpace(Location) && System.IO.Path.IsPathRooted(Location);
			}
		}
		#endregion

		#region Constructors
		public GameSave()
		{
		}
		#endregion

		#region Methods
		private void LoadData()
		{
			using(var fileStream = new FileStream(this.Location, FileMode.Open))
			{
				using(var reader = new BinaryReader(fileStream))
				{
					var key = reader.ReadString();
					var user = reader.ReadString();
					DescriptionData = reader.ReadString();
					SaveData = reader.ReadString();
				}
			}
		}

		public Stream GetDescriptionStream()
		{
			if(!this.IsCached)
				throw new GameSaveNotAvailableException(this);

			if(string.IsNullOrWhiteSpace(DescriptionData))
				LoadData();
			return new MemoryStream(Convert.FromBase64String(DescriptionData));
		}

		public Stream GetDataStream()
		{
			if(!this.IsCached)
				throw new GameSaveNotAvailableException(this);

			if(string.IsNullOrWhiteSpace(SaveData))
				LoadData();
			return new MemoryStream(Convert.FromBase64String(SaveData));
		}
		#endregion
	}
}
